<script setup lang="ts">
import { ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import {
  listDormitoryByPage,
  addDormitory,
  updateDormitory,
  deleteDormitory,
} from "@/api/dormitory";
import type {
  Dormitory,
  DormitoryQueryRequest,
  DormitoryAddRequest,
  DormitoryUpdateRequest,
} from "@/models/dormitory";
import dayjs from "dayjs";

// 宿舍管理相关状态
const dormitories = ref<Dormitory[]>([]);
const dormitoryTotal = ref(0);
const dormitoryCurrentPage = ref(1);
const dormitoryPageSize = ref(6);
const dormitorySearchText = ref("");
const dormitoryIdSearch = ref("");
const dormitoryLoading = ref(false);

// 宿舍编辑弹窗
const dormitoryModalVisible = ref(false);
const dormitoryModalTitle = ref("添加宿舍");
const editingDormitory = ref<DormitoryUpdateRequest>({
  dormitoryId: 0,
  dormitoryName: "",
  buildingId: 0,
});

// 获取宿舍列表
const fetchDormitories = async () => {
  dormitoryLoading.value = true;
  try {
    const queryRequest: DormitoryQueryRequest = {
      current: dormitoryCurrentPage.value,
      pageSize: dormitoryPageSize.value,
      dormitoryName: dormitorySearchText.value,
      dormitoryId: dormitoryIdSearch.value
        ? parseInt(dormitoryIdSearch.value)
        : undefined,
    };
    const res = await listDormitoryByPage(queryRequest);
    if (res.data.code === 0) {
      dormitories.value = res.data.data.records;
      dormitoryTotal.value = res.data.data.total;
    } else {
      message.error("获取宿舍列表失败");
    }
  } catch (error) {
    message.error("获取宿舍列表失败");
  } finally {
    dormitoryLoading.value = false;
  }
};

// 搜索宿舍
const onDormitorySearch = () => {
  dormitoryCurrentPage.value = 1;
  fetchDormitories();
};

// 重置搜索
const handleReset = () => {
  dormitorySearchText.value = "";
  dormitoryIdSearch.value = "";
  dormitoryCurrentPage.value = 1;
  fetchDormitories();
};

// 处理分页变化
const handleDormitoryTableChange = (pagination: any) => {
  dormitoryCurrentPage.value = pagination.current;
  dormitoryPageSize.value = pagination.pageSize;
  fetchDormitories();
};

// 添加宿舍
const handleAddDormitory = () => {
  dormitoryModalTitle.value = "添加宿舍";
  editingDormitory.value = {
    dormitoryId: 0,
    dormitoryName: "",
    buildingId: 0,
  };
  dormitoryModalVisible.value = true;
};

// 编辑宿舍
const handleEditDormitory = (record: Dormitory) => {
  dormitoryModalTitle.value = "编辑宿舍";
  editingDormitory.value = {
    dormitoryId: record.dormitoryId,
    dormitoryName: record.dormitoryName,
    buildingId: record.buildingId,
  };
  dormitoryModalVisible.value = true;
};

// 保存宿舍
const handleSaveDormitory = async () => {
  try {
    if (editingDormitory.value.dormitoryId === 0) {
      console.log(editingDormitory.value);
      // 添加宿舍
      const res = await addDormitory(editingDormitory.value);
      if (res.data.code === 0) {
        message.success("添加成功");
      } else {
        message.error(res.data.message || "添加失败");
      }
    } else {
      // 更新宿舍
      const res = await updateDormitory(editingDormitory.value);
      if (res.data.code === 0) {
        message.success("更新成功");
      } else {
        message.error(res.data.message || "更新失败");
      }
    }
    dormitoryModalVisible.value = false;
    fetchDormitories();
  } catch (error) {
    message.error("操作失败");
  }
};

// 删除宿舍
const handleDeleteDormitory = async (record: Dormitory) => {
  try {
    const res = await deleteDormitory(record.dormitoryId);
    if (res.data.code === 0) {
      message.success("删除成功");
      fetchDormitories();
    } else {
      message.error(res.data.message || "删除失败");
    }
  } catch (error) {
    message.error("删除失败");
  }
};

onMounted(() => {
  fetchDormitories();
});
</script>

<template>
  <a-card class="info-card">
    <template #title>
      <div class="card-title">
        <home-outlined />
        <span>宿舍信息管理</span>
      </div>
    </template>
    <template #extra>
      <a-space>
        <a-input-number
          v-model:value="dormitoryIdSearch"
          placeholder="宿舍ID"
          style="width: 120px"
        />
        <a-input-search
          v-model:value="dormitorySearchText"
          placeholder="搜索宿舍名称"
          style="width: 200px"
          @search="onDormitorySearch"
        />
        <a-button type="primary" @click="handleAddDormitory">
          添加宿舍
        </a-button>
      </a-space>
    </template>

    <a-table
      :dataSource="dormitories"
      :loading="dormitoryLoading"
      :pagination="{
        total: dormitoryTotal,
        current: dormitoryCurrentPage,
        pageSize: dormitoryPageSize,
        showSizeChanger: true,
        showQuickJumper: true,
      }"
      @change="handleDormitoryTableChange"
    >
      <a-table-column
        key="dormitoryId"
        title="宿舍ID"
        data-index="dormitoryId"
      />
      <a-table-column
        key="dormitoryName"
        title="宿舍名称"
        data-index="dormitoryName"
      />
      <a-table-column key="buildingId" title="楼栋ID" data-index="buildingId" />
      <a-table-column
        key="createTime"
        title="创建时间"
        data-index="createTime"
        :customRender="({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')"
      />
      <a-table-column key="action" title="操作">
        <template #default="{ record }">
          <a-space>
            <a @click="handleEditDormitory(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这个宿舍吗？"
              @confirm="handleDeleteDormitory(record)"
            >
              <a style="color: #ff4d4f">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table-column>
    </a-table>

    <!-- 宿舍编辑弹窗 -->
    <a-modal
      v-model:visible="dormitoryModalVisible"
      :title="dormitoryModalTitle"
      @ok="handleSaveDormitory"
    >
      <a-form :model="editingDormitory" layout="vertical">
        <a-form-item label="宿舍名称" required>
          <a-input v-model:value="editingDormitory.dormitoryName" />
        </a-form-item>
        <a-form-item label="楼栋ID" required>
          <a-input-number
            v-model:value="editingDormitory.buildingId"
            style="width: 100%"
            :min="1"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<style scoped>
.info-card {
  margin-bottom: 24px;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  color: #1f1f1f;
}

.card-title .anticon {
  margin-right: 12px;
  font-size: 20px;
  color: #1890ff;
}
</style>
